package com.cy.common.web;

import com.cy.common.pojo.JsonResult;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//此为全局异常的方法
@RestControllerAdvice
public class GlobalExceptionHandler {
    //处理shiro框架异常
    @ExceptionHandler(RuntimeException.class)
    //@ResponseBody
    public JsonResult doHandleRunTimeException(RuntimeException e){
        e.printStackTrace();
        System.out.println("GlobalExceptionHandler.doHandleRuntimeException");
        return new JsonResult(e);
    }
    @ExceptionHandler(ShiroException.class)
    //@ResponseBody
    public JsonResult doHandleShiroException(
            ShiroException e){
      JsonResult r=new JsonResult();
      r.setState(0);
      if(e instanceof UnknownAccountException){
          r.setMessage("账号不存在");
      }else if(e instanceof LockedAccountException){
          r.setMessage("账号禁用");
      }else if(e instanceof IncorrectCredentialsException){
          r.setMessage("密码不正确");
      }else if(e instanceof AuthenticationException){
          r.setMessage("没有权限");
      }else{
          r.setMessage("系统维护中");
      }
      e.printStackTrace();//输出异常在控制台

      return r;
    }
}
